//
//  WBTabBar.swift
//  Weibo
//
//  Created by 任贤斌 on 2016/11/21.
//  Copyright © 2016年 Renkey. All rights reserved.
//

import UIKit

class WBTabBar: UITabBar {
    
    //定义闭包
    var composeClosure: (() -> ())?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(composeBtn)
        //监听按钮的点击事件
        self.composeBtn.addTarget(self, action: #selector(composeBtnDidClick), for: .touchUpInside)
    }
    
    //不希望外界能够访问按钮的点击事件 需要设置私有
    @objc private func composeBtnDidClick() {
        //需要跳转控制器 不能直接在view中处理点击事件
        //应该对外抛出点击事件(代理或者闭包)
        composeClosure?()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //修改内部视图的位置 要重写 layoutSubviews
    override func layoutSubviews() {
        //需要super
        super.layoutSubviews()
        //需要获取 UITabBarButton类型的控件 并且修改frame
        //遍历子视图
        let w = UIScreen.main.bounds.width / 5
        let h = self.bounds.height
        var index = 0
        
        for subView in subviews {
            //判断类型
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
                //修改frame
                subView.frame = CGRect(x: CGFloat(index) * w, y: 0, width: w, height: h)
                /*
                if index == 1 {
                    index += 1
                }
                index += 1
                */
                index += (index == 1 ? 2 : 1)
            }
        }
        //设置撰写按钮的frame
        composeBtn.bounds.size = CGSize(width: w, height: h)
        composeBtn.center = CGPoint(x: self.center.x, y: h * 0.5)
    }
    
    //懒加载
    lazy var composeBtn: UIButton = {
        let btn = UIButton()
        //设置图片
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        //btn.sizeToFit()
        return btn
    }()
}
